﻿using Product.Domain.Entity;
using Product.Domain.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Product.Domain.DomainService
{
    public class SpuDomainService : IDomainService
    {
        private const int DefaultRank = 1;
        private readonly ISkuReposiory _skuReposiory;
        private readonly ISpuReposiory _spuReposiory;
        public SpuDomainService(ISkuReposiory skuReposiory, ISpuReposiory spuReposiory)
        {
            _skuReposiory = skuReposiory;
            _spuReposiory = spuReposiory;
        }

        /// <summary>
        /// 创建spu
        /// </summary>    
        public async Task AddSpu(string spuName, string picUrl, string categoryId, string brandId, List<Specification> specificationList, List<Sku> skuList)
        {
            var skus = new List<Sku>();

            var spu = Spu.AddSpu(spuName, picUrl, categoryId, brandId, specificationList);

            foreach (var item in skuList)
            {
                var sku = new Sku(spu.Id, GenerateSkuNo(),item.Stock, item.PicUrl, item.Specification, item.Price, item.UnitId);
                skus.Add(sku);
            }

            spu.AddSku(skus);

            await _spuReposiory.AddSpu(spu);
        }

        /// <summary>
        /// 生成SkuNo
        /// 规则:年月日+4个顺位
        /// </summary>
        private string GenerateSkuNo()
        {
            try
            {
                var skuNo = string.Empty;
                var skuMaxNo = _skuReposiory.GetTodayMaxSkuNo();
                var yearMonthDay = DateTime.Now.Date.ToString("yyyyMMdd");
                if (!string.IsNullOrWhiteSpace(skuMaxNo))
                {
                    var beforeNo = skuMaxNo.Substring(0, skuMaxNo.LastIndexOf('-') + 1);
                    var afterNo = skuMaxNo.Substring(skuMaxNo.LastIndexOf('-') + 1, 4);
                    var rank = Convert.ToInt32(afterNo) + 1;
                    if (rank > 9999)
                    {
                        throw new DomainException("已超过每天最大新建的Sku数！");
                    }
                    skuNo = beforeNo + rank.ToString().PadLeft(4, '0');
                }
                else
                {
                    skuNo = yearMonthDay + DefaultRank.ToString().PadLeft(4, '0');
                }
                if (string.IsNullOrWhiteSpace(skuNo))
                {
                    throw new DomainException("SkuNo生成失败，SkuNo不能为空！");
                }
                return skuNo;
            }
            catch (Exception ex)
            {
                throw new DomainException($"SkuNo生成异常,异常信息：{ex.Message}");
            }
        }

    }
}
